#include "csdatabaselogin.h"
#include "ui_csdatabaselogin.h"
#include <QMessageBox>

CSDatabaseLogin::CSDatabaseLogin(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CSDatabaseLogin)
{
    ui->setupUi(this);

    si = new CSSettingsInformation;
}

CSDatabaseLogin::~CSDatabaseLogin()
{
    delete si;
    delete ui;
}

void CSDatabaseLogin::on_buttonBox_accepted()
{
    // we need to select the user...
    df = new DataBaseFacade;
    if (df->AuthUserByUserName(this->ui->txtUserName->text(), this->ui->txtPassword->text()) == false)
    {
        QMessageBox::warning(this, "Error", "Login Failed!");
        emit NotLoggedIn();
    }
    else
    {
        emit LoggedIn();
    }

    delete df;
}

void CSDatabaseLogin::on_buttonBox_rejected()
{
    emit this->Canceled();
}

void CSDatabaseLogin::on_btnDatabaseSettings_clicked()
{
    this->sd = new SettingsDialog;
    connect(sd, SIGNAL(DatabaseSettingsUpdated()), this, SLOT(on_DatabaseSettingsUpdated()));
    connect(sd, SIGNAL(DatabaseSettingsAborted()), this, SLOT(on_DatabaseSettingsAborted()));
    this->DisconnectSettings();
    sd->exec();
}

void CSDatabaseLogin::on_DatabaseSettingsUpdated()
{
    this->DisconnectSettings();
    delete sd;
}

void CSDatabaseLogin::on_DatabaseSettingsAborted()
{
    this->DisconnectSettings();
    delete sd;
}

void CSDatabaseLogin::DisconnectSettings()
{
    sd->close();
    disconnect(sd, SIGNAL(DatabaseSettingsUpdated()), this, SLOT(on_DatabaseSettingsUpdated()));
    disconnect(sd, SIGNAL(DatabaseSettingsAborted()), this, SLOT(on_DatabaseSettingsAborted()));
}


void CSDatabaseLogin::on_chkDontShowThisAgain_toggled(bool checked)
{
    if (checked)
    {
        ui->buttonBox->setEnabled(false);
    }
    else
    {
        ui->buttonBox->setEnabled(true);
    }
}

void CSDatabaseLogin::on_btnSingleFile_clicked()
{
    si->WriteSingleFileStore(true);

    if (ui->chkDontShowThisAgain->isChecked())
    {
        si->WriteSingleShowAgain(false);
    }
    else
    {
        si->WriteSingleShowAgain(true);
    }

    emit this->SingleFile();
}
